<template>
  <div>
    <div ref="mapDiv" class="full-width full-height" />
    <q-page-sticky position="top-left" :offset="[15, 15]">
      <div class="row q-gutter-sm">
        <q-btn
          rounded
          :outline="mapFunction === 'mapSelector'"
          class="blur"
          label="选择地图"
          color="primary"
          icon="map"
          @click="mapSelector.show()"
        />
        <template v-if="mapId !== ''">
          <q-btn
            rounded
            label="查看机器人"
            :outline="mapFunction === 'amrInMap'"
            class="blur"
            color="primary"
            icon="toys"
            @click="devicesManagement.show()"
          />
          <q-btn
            rounded
            :outline="mapFunction === 'poseRoute'"
            class="blur"
            label="点位连线"
            color="accent"
            icon="route"
            @click="poseRoute.show()"
          />
          <q-btn
            rounded
            label="运动被阻塞"
            :outline="mapFunction === 'stuckAmrInMap'"
            class="blur"
            v-if="DeadlockList.length !== 0"
            color="red-4"
            icon="https"
            @click="deadlockDevices.show()"
          >
            <q-badge color="red" floating v-if="DeadlockList.length !== 0">{{
              DeadlockList.length
            }}</q-badge>
          </q-btn>
        </template>
      </div>
    </q-page-sticky>
    <map-selector ref="mapSelector" remote @same-group="loadSameGroup" />
    <amr-in-map ref="devicesManagement" />
    <stuck-amr-in-map ref="deadlockDevices" />
    <pose-route ref="poseRoute" :map-id="mapId" />
    <q-inner-loading :showing="loading">
      <q-spinner-facebook size="10rem" color="primary" />
    </q-inner-loading>
  </div>
</template>

<script>
import { computed, onMounted, onUnmounted, provide, ref, watch } from "vue";
import { useQuasar } from "quasar";
import { api } from "boot/axios";
import { useRoute } from "vue-router";
import { status, isConnected } from "src/utils/deviceWs";
import centerWs, {
  closeCenterWs,
  devices,
} from "src/components/rosMapRemote/centerWs";
import { useAPIStore } from "stores/api/index.js";
import PixiMap from "components/rosMapRemote/PixiMap.js";
import { useFunctionsStore } from "stores/functions/index.js";

import MapSelector from "components/rosMapRemote/MapSelector.vue";
import AmrInMap from "components/rosMapRemote/AmrInMap.vue";
import PoseRoute from "components/rosMapRemote/pose/PoseRoute.vue";
import StuckAmrInMap from "components/rosMapRemote/StuckAmrInMap.vue";

export default {
  components: {
    StuckAmrInMap,
    PoseRoute,
    AmrInMap,
    MapSelector,
  },
  setup() {
    const $q = useQuasar();
    const $route = useRoute();
    const mapDiv = ref();
    const mapSelector = ref(null);
    const loading = ref(false);
    provide("amrTypes", [
      {
        label: "所有机器人",
        value: null,
      },
      {
        label: "运输机器人（顶升）",
        value: "transport-lift",
      },
      {
        label: "运输机器人（抓取）",
        value: "transport-catch",
      },
      {
        label: "运输机器人（立体库）",
        value: "transport-as-rs",
      },
    ]);
    provide("poseTypes", [
      {
        label: "库位点（抓取）",
        value: "storage-catch",
      },
      {
        label: "工位点（顶升）",
        value: "station-lift",
      },
      {
        label: "工位点（抓取）",
        value: "station-catch",
      },
      {
        label: "工位点（立体库）",
        value: "station-port",
      },
      {
        label: "无类型",
        value: null,
      },
      {
        label: "反光柱",
        value: "reflector",
      },
      {
        label: "停车位",
        value: "parking-spot",
      },
      {
        label: "待命点",
        value: "standby",
      },
      {
        label: "避让点",
        value: "avoid",
      },
      {
        label: "充电桩点位",
        value: "charger",
      },
      {
        label: "传送点（同层）",
        value: "teleport",
      },
      {
        label: "传送点（电梯）",
        value: "teleport-elevator",
      },
      {
        label: "闸门控制点",
        value: "gate",
      },
      {
        label: "避障控制点",
        value: "narrow",
      },
      {
        label: "速度控制点",
        value: "speed",
      },
    ]);
    provide("navigationTypes", [
      {
        label: "激光SLAM导航",
        value: "slam",
      },
      {
        label: "磁条导航",
        value: "magv",
      },
    ]);
    const pixiMap = PixiMap();
    // const status = inject('status')
    const mapFunction = ref("mapSelector");
    const mode = useFunctionsStore().mode;
    const online = computed(
      () =>
        status.value.centerConnected || !isConnected.value || mode === "server"
    );
    const mapUrl = computed(() =>
      online.value ? useAPIStore().mapUrl + "map/" : useAPIStore().amrUrl
    );
    const poseUrl = computed(() =>
      online.value
        ? useAPIStore().mapUrl + "mapPose/"
        : useAPIStore().amrUrl + "pose/"
    );
    const areaUrl = computed(() =>
      online.value
        ? useAPIStore().mapUrl + "virtualWall/"
        : useAPIStore().amrUrl + "virtualWall/"
    );
    provide("pixiMap", pixiMap);
    provide("mapUrl", mapUrl);
    provide("online", online);
    provide("mapFunction", mapFunction);

    const mapId = ref(useFunctionsStore().remoteMapId);
    provide("mapId", mapId);
    watch(mapId, (value) => {
      initMap();
      useFunctionsStore().remoteMapId = value;
    });
    // 地图组的实体列表
    const mapGroupList = ref([]);
    provide("mapGroupList", mapGroupList);

    // 设备列表
    const devicesList = computed(() =>
      devices.value.filter((amr) => amr.mapID === mapId.value)
    );
    provide("devicesList", devicesList);

    const robList = ref(new Map());

    // 页面打开时
    onMounted(() => {
      centerWs();
      pixiMap.mode = "control";
      if ($route.query.mapID) {
        // 由设备列表跳转过来
        if (mapId.value === $route.query.mapID) {
          initMap();
        } else {
          mapId.value = $route.query.mapID;
        }
      } else {
        if (mapId.value) initMap();
        else mapSelector.value.show();
      }
    });

    // 页面离开时
    onUnmounted(() => {
      closeCenterWs();
      clearTimeout(timer);
    });

    // 初始化配置
    function initPixi() {
      mapDiv.value.innerHTML = "";
      pixiMap.div = mapDiv.value;
      pixiMap.mode = "control";
      // 创建舞台
      pixiMap.stage = pixiMap.createStage({
        div: mapDiv.value,
        width: mapDiv.value.offsetWidth,
        height: mapDiv.value.offsetHeight,
      });
      const poseImg = new Image();
      poseImg.src = "map/pose.png";
      pixiMap.poseImg = poseImg;
      // 初始化元素
      pixiMap.initStage();
    }

    function initMap() {
      // 清空内容，初始化配置
      initPixi();
      if (!mapId.value) return;
      loadMap();
    }

    function loadMap() {
      // 显示loading
      loading.value = true;
      // 获取地图数据
      api
        .get(mapUrl.value + "id/" + mapId.value)
        .then((res) => {
          // 判断出现状态码204表示请求已经执行成功，但没有内容是重新选择地图
          if (res.status !== 200) {
            loading.value = false;
          } else {
            const image = new Image();
            if (res.data.format === "landmark") {
              pointList.value = JSON.parse(res.data.mapBase64).poses;
              res.data.mapBase64 =
                "iVBORw0KGgoAAAANSUhEUgAABkAAAAZACAIAAACubhnwAAAAAXN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AJAmsAAAAABIE1gAAAAApAksAAAAANIEFgAAAABpAgsAAACANIEFAAAAQJrAAgAAACBNYAEAAACQJrAAAAAASBNYAAAAAKQJLAAAAADSBBYAAAAAaQILAAAAgDSBBQAAAECawAIAAAAgTWABAAAAkCawAAAAAEgTWAAAAACkCSwAAAAA0gQWAAAAAGkCCwAAAICw7QGk1adQ1YMl4wAAAABJRU5ErkJggg==";
              res.data.resolution = 0.025;
              res.data.x = -20;
              res.data.y = -20;
            }
            pixiMap.mapFormat = res.data.format;

            if (!res.data.mapRemote64) {
              image.src =
                "data:image/" +
                (res.data.format === "landmark" ? "png" : res.data.format) +
                ";base64," +
                res.data.mapBase64;
            } else {
              image.src =
                "data:image/" +
                (res.data.format === "landmark" ? "png" : res.data.format) +
                ";base64," +
                res.data.mapRemote64;
            }
            // 图片加载成功
            image.onload = () => {
              // 渲染地图
              pixiMap.map = pixiMap.createMap({
                resolution: res.data.resolution,
                x: res.data.x,
                y: res.data.y,
                img: image,
              });
              // 创建机器人
              const robotImg = new Image();
              robotImg.src = "map/arrow.png";
              robotImg.onload = () => {
                createRobots(robotImg);
                updateRobots(robotImg);
              };
              // 讲各元素加载到舞台上
              pixiMap.updateStage();
              // 隐藏loading
              loading.value = false;
              // 加载点位路径
              if (pixiMap.mapFormat === "landmark") {
                drawRoutes(pointList.value);
              } else {
                loadRoutes();
              }
              // 加载虚拟墙
              loadWalls();
              loadSafety();
            };
            image.onerror = () => {
              $q.notify({ message: "加载地图失败", type: "negative" });
              // 隐藏loading
              loading.value = false;
            };
          }
        })
        .catch((err) => {
          console.error(err);
          $q.notify({ message: "获取地图失败", type: "negative" });
          loading.value = false;
        });
    }

    let timer;

    // 刷新机器人位置
    function updateRobots(img) {
      devicesList.value.forEach((rob) => {
        robList.value.get(rob.device).x = rob.x;
        robList.value.get(rob.device).y = -rob.y;
        // pixijs用的是弧度制，角度转弧度
        robList.value.get(rob.device).rotation =
          ((90 +
            pixiMap.toTheta({
              x: rob.qx || 0,
              y: rob.qy || 0,
              z: rob.qz || 0,
              w: rob.qw || 0,
            })) *
            Math.PI) /
          180;
      });
      timer = setTimeout(() => {
        updateRobots(img);
        getOccupies();
        getDeadlock();
      }, 1000);
    }

    // 机器人组的颜色
    const robotColor = ref([
      "0x1E90FF",
      "0xEE82EE",
      "0x40E0D0",
      "0x3CB371",
      "0xFFFF00",
      "0xFF6347",
    ]);

    // 绘制机器人组
    function createRobots(img) {
      devicesList.value.forEach((rob, index) => {
        // 渲染机器人
        // 将机器人放入map中，便于通过device来获取元素对象
        robList.value.set(rob.device, pixiMap.createRobot({ image: img }));
        robList.value.get(rob.device).tint = robotColor.value[index % 6];
        // 将机器人加入场景
        pixiMap.robContainer.addChild(robList.value.get(rob.device));
      });
      if (devicesList.value.length !== 0) {
        pixiMap.lookAt({
          x: devicesList.value[0].x,
          y: devicesList.value[0].y,
        });
      } else {
        // pixiMap.lookAt(pointList.value[0].pose.position)
      }
    }

    const occupies = ref({});
    provide("occupies", occupies);

    // 获取机器人占用的点位
    function getOccupies() {
      api
        .get(useAPIStore().centerUrl + "navigation/occupies/" + mapId.value)
        .then((res) => {
          occupies.value = res.data;
          // 清空占用清空
          pixiMap.drawRail();
          // 遍历占用情况 开始赋于大小及颜色
          for (const v in res.data) {
            pixiMap.pointContainer
              .getChildByName(v)
              .scale.set(0.8 / pixiMap.poseImg.width);
            if (!robList.value) {
              pixiMap.pointContainer.getChildByName(v).tint = robList.value.get(
                res.data[v]
              ).tint;
            } else {
              pixiMap.pointContainer.getChildByName(v).tint =
                robotColor.value[0];
            }
            pixiMap.pointContainer.getChildByName(v).tint =
              robList.value.get(res.data[v]).tint || robotColor.value[0];
          }
        });
    }

    const stuckAmrList = ref([]);
    provide("stuckAmrList", stuckAmrList);

    // 获取死锁点
    function getDeadlock() {
      api
        .get(
          useAPIStore().centerUrl + "navigation/deadlock/mapID/" + mapId.value
        )
        .then((res) => {
          stuckAmrList.value = res.data;
          // 每次获取时清空
          pixiMap.lockList = [];
          // 遍历获取死锁点id
          stuckAmrList.value.forEach((item) => {
            pixiMap.lockList.push(item.lastPose);
          });
          // 画死锁点
          pixiMap.drawDead();
        });
    }

    // 保存点位
    function savePoints() {
      api
        .put(poseUrl.value + "ros/" + mapId.value, pointList.value)
        .then(() => {
          drawRoutes(pointList.value);
          $q.notify({ message: "保存成功", type: "positive" });
          api
            .get(useAPIStore().centerUrl + "navigation/reset/" + mapId.value)
            .then((rs) => {
              if (rs.data === "done") {
                $q.notify({
                  message: "调度系统已重载当前地图点位",
                  type: "positive",
                });
              }
            });
        })
        .catch((err) => {
          console.error(err);
          $q.notify({ message: "保存失败", type: "negative" });
        });
    }

    provide("savePoints", savePoints);
    // 点位列表
    const pointList = ref([]);
    provide("pointList", pointList);
    const poseMap = ref({});
    provide("poseMap", poseMap);

    // 从数据库获取最新点位列表
    function loadRoutes() {
      api.get(poseUrl.value + "ros/mapID/" + mapId.value).then((rs) => {
        pointList.value = rs.data;
        drawRoutes(pointList.value);
      });
    }

    provide("loadRoutes", loadRoutes);

    // 显示路线
    function drawRoutes(list) {
      pixiMap.drawRail(list);
      poseMap.value = {};
      list.forEach((item) => {
        poseMap.value[item.id] = item;
      });
    }

    provide("drawRoutes", drawRoutes);

    // 虚拟墙列表
    const wallList = ref([]);

    // 从数据库获取最新虚拟墙列表
    function loadWalls() {
      api.get(areaUrl.value + "mapID/" + mapId.value).then((res) => {
        wallList.value = res.data;
        drawWalls(wallList.value);
      });
    }

    // 显示虚拟墙
    function drawWalls(list) {
      pixiMap.drawWall(list);
    }

    const safetyList = ref([]);
    provide("safetyList", safetyList);

    function loadSafety() {
      api
        .get(useAPIStore().mapUrl + "polygon/mapID/" + mapId.value)
        .then((res) => {
          safetyList.value = res.data;
          pixiMap.drawSafety(safetyList.value);
        });
    }

    provide("loadSafety", loadSafety);

    return {
      pixiMap,
      mapDiv,
      mapSelector,
      mapFunction,
      poseRoute: ref(),
      devicesManagement: ref(),
      deadlockDevices: ref(),
      loading,
      devicesList,
      loadSameGroup(val) {
        mapGroupList.value = val;
      },
      fab: ref(true),
      mapId,
      DeadlockList: stuckAmrList,
    };
  },
};
</script>

<style scoped>
.blur {
  background: rgba(255, 255, 255, 1);
  backdrop-filter: blur(15px) brightness(175%);
}
</style>
